# -*- coding: utf-8 -*-
"""
-----------------------------------------------------------------
    File Name   : table_util.py
    Description : 表格输出处理工具
    Author      : DuanGe
    Created On  : 2024/11/19
    Email       : duangeali@aliyun.com
    Version     : 1.0.0
    Copyright   : Copyright (c) 2024 DuanGe
    License     : Apache License 2.0
-----------------------------------------------------------------
"""
from prettytable import PrettyTable

from common.common import error_tip
from common.log import table_logger, add_logs


def list_table(list_data: list[dict], table_headers: list[str], columns: list[str]):
    """
    以表格形式展示数据

    :param list_data: 包含字典的列表，每个字典代表一行数据
    :param table_headers: 表头列表
    :param columns: 要显示数据的属性列表
    """
    operation = "表格输出"
    msg = f"数据长度: {0 if list_data is None else len(list_data)}, 表头: {table_headers}, 显示的属性: {columns}"
    try:
        if not list_data:
            raise ValueError("list_data is empty")
        if len(table_headers) != len(columns):
            raise ValueError("length of table_headers is not equal to that of columns")
        # 创建PrettyTable对象
        table = PrettyTable()
        # 设置表头
        table.field_names = table_headers
        # 遍历数据并添加到表格中
        for row in list_data:
            if not isinstance(row, dict):
                raise TypeError("row of list_data must be a dict")
            if any(col not in row for col in columns):
                raise KeyError("row of list_data is missing a required key")
            # 根据columns中的属性提取数据
            row_data = [row[col] for col in columns]
            table.add_row(row_data)
        # 打印表格
        print(table)
        # 记录日志
        add_logs(table_logger, "INFO", operation, msg)
    except (ValueError, TypeError, KeyError, IndexError, AttributeError, Exception) as e:
        err_msg = {
            ValueError: "值错误",
            TypeError: "类型错误",
            KeyError: "键错误",
            IndexError: "索引错误",
            AttributeError: "属性错误",
            Exception: "发生未知错误",
        }.get(type(e), "发生未知错误")
        error_tip(f"{operation}失败, {err_msg}")
        # 记录日志
        add_logs(table_logger, "ERROR", operation, msg, err_msg, e)
